#include "hwMqttHandler.h"
#include "hxMqttConfig.h"
#include "ScnsInclude.h"
#include "rtc.h"
#include "extra/widgets/dclock/lv_dclock.h"
#include "gui_guider.h"

void hxMqttConnectHandler(void)
{
    scnsDelayMs(100);
    hxMqttPublishSubscribe("hxmqtt/led",0);
}

void hxMqttReceiveHandler(const unsigned char*topic,unsigned int topicLen,const unsigned char*data,unsigned int dataLen)
{
    if(hxMqttStringMatch("hxmqtt/led",topic,topicLen))
    {
        if(hxMqttStringMatch("on",data,dataLen))
        {
            scnsLedSet(SCNS_LED_D6,SCNS_LED_SWITCH_ON);
        }
        else if(hxMqttStringMatch("off",data,dataLen))
        {
            scnsLedSet(SCNS_LED_D6,SCNS_LED_SWITCH_OFF);
        }
    }
}

void hwMqttSend(void)
{
    hxMqttPing();
    {
        const uint64 t=scnsTimerGetUs();
        static uint64 lastUs=0;
        if(t>=lastUs+20*1000)
        {
            lastUs=t;
            static int cnt=0;
            ++cnt;
            char str[128];
            if(cnt>10){cnt=0;}
            if(cnt==0)
            {
                hxMqttConnect();
                hxSPrintf(str,"%f",scnsBh1750Result[SCNS_BH1750_1].lux);
                hxMqttPublishQos0String("hxmqtt/sensor/bh1750",str);
            }
            if(cnt==1)
            {
                hxSPrintf(str,"%d",scnsDht11Result[SCNS_DHT11_1].humidity);
                hxMqttPublishQos0String("hxmqtt/sensor/humidity",str);

            }
            if(cnt==2)
            {
                hxSPrintf(str,"%d",scnsDht11Result[SCNS_DHT11_1].temperature);
                hxMqttPublishQos0String("hxmqtt/sensor/temperature1",str);
            }
            if(cnt==3)
            {
                hxSPrintf(str,"%f",scnsDs18b20Result[SCNS_DS18B20_1].temperature);
                hxMqttPublishQos0String("hxmqtt/sensor/temperature2",str);
            }
            if(cnt==4)
            {
                hxSPrintf(str,
                          "%04d-%02d-%02d %02d:%02d:%02d",
                          2000+__LL_RTC_CONVERT_BCD2BIN(LL_RTC_DATE_GetYear(RTC)),
                          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_DATE_GetMonth(RTC)),
                          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_DATE_GetDay(RTC)),
                          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TIME_GetHour(RTC)),
                          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TIME_GetMinute(RTC)),
                          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TIME_GetSecond(RTC)));
                hxMqttPublishQos0String("hxmqtt/date",str);
            }

        }
    }
}
